package com.ukao.pad.ui.orders;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.ukao.pad.R;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.AddressList;
import com.ukao.pad.bean.serviceTimeBean;

import com.ukao.pad.consts.GlobalConsts;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.dialog.AddressDialogFragment;
import com.ukao.pad.dialog.ChooseDialogFragment;
import com.ukao.pad.dialog.DialogTool;
import com.ukao.pad.eventbus.ChooseCardEvent;
import com.ukao.pad.presenter.PlaceOrderPresenter;
import com.ukao.pad.ui.stokin.StockinFragment;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.L;
import com.ukao.pad.utils.MyDateUtils;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.PlaceoOrderView;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.pad.utils.MyDateUtils.getTime;


/**
 * 客户信息右边下单
 */
public class CreateOrdersUserInfoRightFragment extends MvpFragment<PlaceOrderPresenter> implements PlaceoOrderView {


    Unbinder unbinder;
    @BindView(R.id.submit_btn)
    Button mSubmitBtn;
    @BindView(R.id.user_info_right_bt1)
    Button mRightBt1;
    @BindView(R.id.user_info_right_bt2)
    Button mRightBt2;
    @BindView(R.id.user_info_pick_up_time)
    LinearLayout mPickUpTime;
    @BindView(R.id.user_info_user_remark_et)
    EditText mUserRemarkEt;
    @BindView(R.id.user_info_admin_remark_et)
    EditText mAdminRemarkEt;
    @BindView(R.id.user_info_right_bt3)
    Button mRightBt3;
    @BindView(R.id.user_info_delivery_time)
    LinearLayout mDeliveryTime;
    @BindView(R.id.fragment_create_orders_user_info_right_toolbar)
    Toolbar fragmentCreateOrdersUserInfoRightToolbar;
    @BindView(R.id.user_info_right_tab1)
    RadioButton userInfoRightTab1;
    @BindView(R.id.user_info_right_tab2)
    RadioButton userInfoRightTab2;
    @BindView(R.id.pickup_regionalDesc)
    TextView pickupRegionalDesc;
    @BindView(R.id.pickup_detail)
    TextView pickupDetail;
    @BindView(R.id.pickup_add_address_layout)
    LinearLayout pickupAddAddressLayout;
    @BindView(R.id.pickup_address_layout)
    LinearLayout pickupAddressLayout;
    @BindView(R.id.user_info_right_tab5)
    RadioButton userInfoRightTab5;
    @BindView(R.id.user_info_right_tab6)
    RadioButton userInfoRightTab6;

    @BindView(R.id.send_regionalDesc)
    TextView sendRegionalDesc;
    @BindView(R.id.send_detail)
    TextView sendDetail;
    @BindView(R.id.user_info_right_tab4)
    RadioButton userInfoRightTab4;
    @BindView(R.id.subtract_btn)
    StateImageView subtractBtn;
    @BindView(R.id.count)
    EditText count;
    @BindView(R.id.add_btn)
    StateImageView addBtn;
    @BindView(R.id.take_mag)
    TextView takeMag;
    @BindView(R.id.user_info_right_add_address_layout)
    LinearLayout userInfoRightAddAddressLayout;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.user_info_right_tab3)
    RadioButton userInfoRightTab3;
    @BindView(R.id.send_msg)
    TextView sendMsg;
    @BindView(R.id.send_add_address_layout)
    LinearLayout sendAddAddressLayout;
    @BindView(R.id.send_address_layout)
    LinearLayout sendAddressLayout;
    private TimePickerView pvCustomTime;
    private String name = "";
    private String phone = "";
    private String userId;
    private String userSex;
    private ArrayList<AddressList> mAddressData = new ArrayList<>();
    private ArrayList<serviceTimeBean.ListBean> mServiceData;

    private String addrId = "";
    public String takeDate = "";
    private String sendDate = "";
    private String takeMode;  //取件方式的flag
    private String storeId; //门店id


    public static CreateOrdersUserInfoRightFragment newInstance(String param1, String param2, String userId, String sex,String storeId) {
        CreateOrdersUserInfoRightFragment fragment = new CreateOrdersUserInfoRightFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, userId);
        args.putString(ARG_PARAM4, sex);
        args.putString(ARG_PARAM5,storeId);
        fragment.setArguments(args);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            name = (String) getArguments().get(ARG_PARAM1);
            phone = (String) getArguments().get(ARG_PARAM2);
            userId = (String) getArguments().get(ARG_PARAM3);
            userSex = getArguments().getString(ARG_PARAM4);
            storeId=getArguments().getString(ARG_PARAM5);
        }
    }

    @Override
    protected PlaceOrderPresenter createPresenter() {
        return new PlaceOrderPresenter(this);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_create_orders_user_info_right, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
        mvpPresenter.getAddressRequest(_mActivity, userId);
        mvpPresenter.serviceTimeData(_mActivity);   //获取时间段
    }

    @Override
    protected void initView() {
        pickupAddAddressLayout.setVisibility(View.GONE);
        userInfoRightAddAddressLayout.setVisibility(View.INVISIBLE);
        mPickUpTime.setVisibility(View.INVISIBLE);
        takeMag.setVisibility(View.INVISIBLE);
        sendMsg.setVisibility(View.INVISIBLE);
        mDeliveryTime.setVisibility(View.INVISIBLE);
        sendAddAddressLayout.setVisibility(View.INVISIBLE);
        sendAddressLayout.setVisibility(View.GONE);
        takeDate = MyDateUtils.getDate();
        sendDate = MyDateUtils.getDate();
        mRightBt1.setText(getTime(Calendar.getInstance().getTime(), "MM—dd EEE"));
        mRightBt3.setText(getTime(Calendar.getInstance().getTime(), "MM—dd EEE"));
    }
    @Override
    protected void initListener() {
        super.initListener();
    }
    private void fillData(List<AddressList> mAddressList) {

        if (!CheckUtils.isEmpty(mAddressList)) {
            mAddressData.clear();
            mAddressData.addAll(mAddressList);
            for (AddressList addressList : mAddressList) {
                if (addressList.getDef() == 1) {
                    setFillAddressData(addressList);
                }
            }


        }

    }

    private void setFillAddressData(AddressList mdefAddress) {
        Log.d("数据", "setFillAddressData: ");
        if (userInfoRightTab2.isChecked()) {
            sendAddressLayout.setVisibility(View.VISIBLE);
            pickupAddAddressLayout.setVisibility(View.VISIBLE);
        } else {
            Log.d("隐藏了", "setFillAddressData: ");
            pickupAddAddressLayout.setVisibility(View.INVISIBLE);
            sendAddressLayout.setVisibility(View.INVISIBLE);
        }
        userInfoRightAddAddressLayout.setVisibility(View.GONE);
        sendAddAddressLayout.setVisibility(View.GONE);
        pickupRegionalDesc.setText(mdefAddress.getPhone() + " " + mdefAddress.getName());
        pickupDetail.setText(mdefAddress.getRegionalDesc() + " " + mdefAddress.getDetail());

        addrId = mdefAddress.getId() + "";
        sendRegionalDesc.setText(mdefAddress.getPhone() + " " + mdefAddress.getName());
        sendDetail.setText(mdefAddress.getRegionalDesc() + " " + mdefAddress.getDetail());


    }


    @OnClick({R.id.user_info_right_bt1, R.id.user_info_right_bt2, R.id.user_info_right_bt3, R.id.user_info_right_add_address_layout,
            R.id.pickup_add_address_layout, R.id.send_address_layout, R.id.send_add_address_layout, R.id.submit_btn,R.id.subtract_btn,R.id.add_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.submit_btn:
                String userRemark = getText(mUserRemarkEt);
                if (CheckUtils.isEmpty(addrId) && userInfoRightTab2.isChecked()) {
                    T.show("请添加地址");
                    return;
                } else if (CheckUtils.isEmpty(addrId) && userInfoRightTab4.isChecked()) {
                    T.show("请添加地址");
                    return;
                }

                HashMap mHashMap = new HashMap<String, String>();
                mHashMap.put("userId", userId);
                mHashMap.put("createCnt",getText(count));
                String priority = userInfoRightTab5.isChecked() ? "0" : "1";
                takeMode = userInfoRightTab1.isChecked() ? "1" : "2";
                String sendMode = userInfoRightTab3.isChecked() ? "1" : "2";
                mHashMap.put("priority", priority);/*订单优先级 0.普通 1.加急*/
                mHashMap.put("takeMode", takeMode);/*取件方式1.客户送到店 2.上门取件*/
                mHashMap.put("sendMode", sendMode);/*送件方式 1.客户到店取 2.上门送件*/
                mHashMap.put("userRemark", userRemark);/*用户订单备注*/
                if (userInfoRightTab1.isChecked()) {
                    mHashMap.put("takeDate", "");/*取件(衣)日期*/
                } else {
                    String[] takeTime = getText(mRightBt2).split("-");
                    mHashMap.put("takeDate", takeDate);/*取件(衣)日期*/
                    if (takeTime.length == 2) {
                        mHashMap.put("takeTimeStart", takeTime[0]);/*取件(衣)起始时间段*/
                        mHashMap.put("takeTimeEnd", takeTime[1]);/*取件(衣)起始时间段*/
                    }
                }
                if (userInfoRightTab2.isChecked()) {
                    mHashMap.put("takeAddrId", addrId);
                }//取件用户地址id
                if (userInfoRightTab4.isChecked()) {
                    mHashMap.put("sendDate", sendDate);/*送件(衣)日期*/
                    mHashMap.put("sendAddrId", addrId);//送件用户地址id
                }
                mHashMap.put("remark", getText(mAdminRemarkEt));/*订单管理备注*/
                mHashMap.put("accessToken", SaveParamets.getToken(_mActivity));
                mHashMap.put("storeId",storeId);
                L.i("mHashMap="+mHashMap.toString());
                mvpPresenter.orderInfoAddRequest(mHashMap);
                break;
            case R.id.user_info_right_bt1:

                DialogTool.getSingleton().showDateQuantumPicker(6, mRightBt3, mRightBt1, _mActivity, mOnGetTimeListener);
                break;
            case R.id.user_info_right_bt2:   //取件时间段
                if (CheckUtils.isEmpty(mServiceData)) return;
                ChooseDialogFragment chooseTime = new ChooseDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putString("Type", GlobalConsts.CREATE_ORDERS_ENTER);
                bundle.putParcelableArrayList("chooseTime", mServiceData);
                bundle.putString("time", takeDate);
                chooseTime.setArguments(bundle);
                chooseTime.show(getChildFragmentManager(), "chooseTime");
                break;
            case R.id.user_info_right_bt3:  //送件时间

                DialogTool.getSingleton().showDateQuantumPicker(30, mRightBt3, mRightBt1, activity, mOnSendTimeListener);
                break;
            case R.id.user_info_right_add_address_layout:
                start(UserInfoRightAddAddressFragment.newInstance(name, phone, userId, userSex, false));
                break;
            case R.id.send_add_address_layout:

                start(UserInfoRightAddAddressFragment.newInstance(name, phone, userId, userSex, false));

                break;
            case R.id.pickup_add_address_layout:   //取件地址
                showAddressDialog();
                break;
            case R.id.send_address_layout:
                showAddressDialog();
                break;
            case  R.id.subtract_btn :/*减去*/
                if (!CheckUtils.isEmpty(getText(count))) {
                    int clothingCount = Integer.valueOf(getText(count));
                    if (clothingCount>0){
                        clothingCount=clothingCount-1;
                        String  strclothingCount=String.valueOf(clothingCount);
                        count.setText(strclothingCount);
                        count.setSelection(strclothingCount.length());
                    }
                }




                break;

            case  R.id.add_btn:/*加*/
                String   strcount=getText(count);
                if (!CheckUtils.isEmpty(strcount)){
                    int  clothingCount1=Integer.valueOf(strcount);
                    clothingCount1=clothingCount1+1;
                     String  strclothingCount1=String.valueOf(clothingCount1);
                    count.setText(strclothingCount1);
                    count.setSelection(strclothingCount1.length());
                }else{
                    count.setText("1");
                    count.setSelection(1);
                }




                break;


        }
    }

    private TimePickerView.OnTimeSelectListener mOnSendTimeListener = new TimePickerView.OnTimeSelectListener() {


        @Override
        public void onTimeSelect(Date date, View v) {
            sendDate = MyDateUtils.formatDate(date);
            mRightBt3.setText(getTime(date, "MM—dd EEE"));

        }
    };

    private TimePickerView.OnTimeSelectListener mOnGetTimeListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            takeDate = MyDateUtils.formatDate(date);

            mRightBt1.setText(getTime(date, "MM—dd EEE"));


        }
    };

    public void showAddressDialog() {
        AddressDialogFragment mAddressDialog = new AddressDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("address", mAddressData);
        mAddressDialog.setArguments(bundle);
        mAddressDialog.show(getChildFragmentManager(), "address");
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(ChooseCardEvent event) {
        switch (event.getMessage()) {
            case update:  //更新当前时间
                if (event.getData() != null) {
                    serviceTimeBean.ListBean mItem = (serviceTimeBean.ListBean) event.getData();
                    mRightBt2.setText(mItem.getTime());
                    for (serviceTimeBean.ListBean item : mServiceData) {
                        if (mItem.getId() == item.getId()) {
                            item.setIscheck(true);
                        } else {
                            item.setIscheck(false);
                        }
                    }
                }

                break;

            case sendaddress:  /*添加地址成功*/
                mvpPresenter.getAddressRequest(_mActivity, userId);

                break;
            case aad_address:  //接收确定地址
                setDeliveryAddressData((AddressList)event.getData());
                break;
            case address_go: /*跳转地址页面*/
                UserInfoRightAddAddressFragment addAddress = UserInfoRightAddAddressFragment.newInstance(name, phone, userId, userSex, false);
                start(addAddress);
                break;
        }
    }

    /**
     * 设置送件地址数据
     */
    private  void  setDeliveryAddressData(AddressList address){
        pickupRegionalDesc.setText(address.getPhone() + " " + address.getName());
        pickupDetail.setText(address.getRegionalDesc() + " " + address.getDetail());
        addrId = address.getId() + "";
        sendRegionalDesc.setText(address.getPhone() + " " + address.getName());
        sendDetail.setText(address.getRegionalDesc() + " " + address.getDetail());
    }

    @OnCheckedChanged({R.id.user_info_right_tab1, R.id.user_info_right_tab2, R.id.user_info_right_tab3, R.id.user_info_right_tab4, R.id.user_info_right_tab5, R.id.user_info_right_tab6})
    public void onChekChanged(CompoundButton view, boolean check) {
        if (check) {
            switch (view.getId()) {
                case R.id.user_info_right_tab1:
                    showTakeRadio();
                    userInfoRightTab3.setChecked(true);
                    break;
                case R.id.user_info_right_tab2:  //上门取件tab
                    showSendRadio();
                    userInfoRightTab4.setChecked(true);
                    break;
                case R.id.user_info_right_tab3:
                    showTakeRadio1();
                    break;
                case R.id.user_info_right_tab4:
                    showsendRadio1();


                    break;
                case R.id.user_info_right_tab5:
                    break;
                case R.id.user_info_right_tab6:
                    break;
            }
        }
    }

    /**
     * 送件方式 顾客送到店
     */
    private void showsendRadio1() {
        mDeliveryTime.setVisibility(View.VISIBLE);
        sendMsg.setVisibility(View.VISIBLE);
        if (CheckUtils.isEmpty(mAddressData)) {
            sendAddressLayout.setVisibility(View.GONE);
            sendAddAddressLayout.setVisibility(View.VISIBLE);
        } else {
            sendAddAddressLayout.setVisibility(View.GONE);
            sendAddressLayout.setVisibility(View.VISIBLE);
        }
    }
    /**
     * 取件方式 顾客到店取
     */
    private void showTakeRadio1() {
        mDeliveryTime.setVisibility(View.INVISIBLE);
        sendAddAddressLayout.setVisibility(View.INVISIBLE);
        sendAddressLayout.setVisibility(View.INVISIBLE);
        sendMsg.setVisibility(View.INVISIBLE);
    }


    /**
     * 送件方式 上门取件
     */
    public void showSendRadio() {
        takeMag.setVisibility(View.VISIBLE);
        mPickUpTime.setVisibility(View.VISIBLE);
        if (CheckUtils.isEmpty(mAddressData)) {
            userInfoRightAddAddressLayout.setVisibility(View.VISIBLE);
            pickupAddAddressLayout.setVisibility(View.GONE);
        } else {
            userInfoRightAddAddressLayout.setVisibility(View.GONE);
            pickupAddAddressLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 取件方式 顾客送到店
     */
    public void showTakeRadio() {
        mPickUpTime.setVisibility(View.INVISIBLE);
        takeMag.setVisibility(View.INVISIBLE);
        mPickUpTime.setVisibility(View.INVISIBLE);
        pickupAddAddressLayout.setVisibility(View.GONE);
        userInfoRightAddAddressLayout.setVisibility(View.GONE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void addressDataSucceed(ArrayList<AddressList> mData) {

        fillData(mData);
    }

    @Override
    public void serviceTimeSucceed(ArrayList<serviceTimeBean.ListBean> mServiceTime) {
        this.mServiceData = mServiceTime;
        if (!CheckUtils.isEmpty(mServiceData)) {
            serviceTimeBean.ListBean mData = mServiceTime.get(0);
            mRightBt2.setText(mData.getTime());
            mData.setIscheck(true);
        }


    }

    @Override
    public void loadFail(String message) {
        T.show(message);
    }
    private final  static String CUSTOMER_SEND_STORE="1";  //顾客送到店
    @Override
    public void orderInfoAddSucceed(String strOrderNo) {
        switch (takeMode) {
            case CUSTOMER_SEND_STORE:
                //跳转入库界面
                if (getParentFragment() instanceof UserInfoFragment) {
                    ((UserInfoFragment) getParentFragment()).start(StockinFragment.newInstance(strOrderNo));
                }
                break;
            case "2":
//                if (getParentFragment() instanceof UserInfoFragment) {
//                    ((UserInfoFragment) getParentFragment()).start(OrderQuiryFragment.newInstance(strorderNo, ""));
//                }

                break;
        }


    }
}
